<template>
  <div class="app-container">
    <!--    面包屑导航 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>社区资产</el-breadcrumb-item>
      <el-breadcrumb-item>单元信息</el-breadcrumb-item>
    </el-breadcrumb>
    <br>

    <!--    模糊查询-->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 
        @clear="getList"：当点击清除按钮清空输入内容时，触发 getList 方法
        当用户在输入框中按下回车键时，触发 handleQuery 方法。.native 表示监听组件根元素的原生事件。
        clearable：显示清除按钮，点击可清空输入内容。
      -->
      <el-form-item label="单元名称" prop="unitName">
        <el-input v-model="queryParams.unitName" placeholder="请输入单元名称" clearable @clear="getList" size="small"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="单元编号" prop="unitCode">
        <el-input v-model="queryParams.unitCode" placeholder="请输入单元编号" clearable @clear="getList" size="small"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="是否有电梯" prop="unitHaveElevator" label-width="90px">
        <el-select v-model="queryParams.unitHaveElevator" placeholder="请选择是否有电梯" clearable @clear="getList"
                   size="small">
          <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                     :value="dict.dictValue"/>
        </el-select>
      </el-form-item>
      <el-form-item label="所属楼栋" prop="buildingId">
        <el-select v-model="queryParams.buildingId" placeholder="所属楼栋" clearable @clear="getList" size="small">
          <el-option v-for="item in buildOptions" :key="item.buildingId" :label="item.buildingName"
                     :value="item.buildingId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <!--      小区几期-->
      <el-form-item style="margin-left: 30px">
        <el-select v-model="queryParams.communityId" @change="selectedCommunity()"
                   style="border: 0;position: relative;" filterable placeholder="请选择小区"
                   class="avatar-container right-menu-item hover-effect">
          <el-option v-for="item in options" :key="item.communityId" :label="item.communityName"
                     :value="item.communityId">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <!--    CRUD+导出按钮-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport">导出
        </el-button>
      </el-col>
    </el-row>
    <br>

    <!--    楼栋信息列表-->
    <el-table v-loading="loading" :data="unitList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="50" align="center">
      </el-table-column>
      <el-table-column label="单元id" align="center" prop="unitId"/>
      <el-table-column label="小区名称" align="center" prop="communityName"/>
      <el-table-column label="楼栋" align="center" prop="buildingName"/>
      <el-table-column label="单元名称" align="center" prop="unitName"/>
      <el-table-column label="单元编号" align="center" prop="unitCode"/>
      <el-table-column label="层数" align="center" prop="unitLevel"/>
      <el-table-column label="建筑面积" align="center" prop="unitAcreage"/>
      <el-table-column label="是否有电梯" align="center" prop="unitHaveElevator">
        <template slot-scope="scope">
          {{ scope.row.unitHaveElevator != 0 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormat"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>

    <!--    分页器 -->
    <div class="block" style="margin-top:15px;">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="queryParams.nowPage" :page-sizes="[5, 10, 15, 20]" :page-size="queryParams.pageSize"
                     layout="total,sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>


    <!--    添加or修改对话框-->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="楼栋" prop="buildingId">
          <el-select v-model="form.buildingId" filterable placeholder="请选择楼栋" @change="selectedBuildingId"
                     class="avatar-container right-menu-item hover-effect"
                     :disabled="this.form.buildingId!==''?true:false">
            <el-option
                v-for="item in buildOptions"
                :key="item.buildingId"
                :label="item.buildingName"
                :value="item.buildingId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单元名称" prop="unitName">
          <el-input v-model="form.unitName" placeholder="请输入单元名称"/>
        </el-form-item>
        <el-form-item label="单元编号" prop="unitCode">
          <el-input v-model="form.unitCode" placeholder="请输入单元编号"/>
        </el-form-item>
        <el-form-item label="层数" prop="unitLevel">
          <el-input type="number" v-model="form.unitLevel" placeholder="请输入层数"/>
        </el-form-item>
        <el-form-item label="建筑面积" prop="unitAcreage">
          <el-input v-model="form.unitAcreage" placeholder="请输入建筑面积"/>
        </el-form-item>
        <el-form-item label="是否有电梯" prop="unitHaveElevator" label-width="82px">
          <el-radio-group v-model="form.unitHaveElevator">
            <el-radio
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  // 全局刷新
  inject: ['reload'],

  data() {
    return {
      // 查询参数
      queryParams: {
        nowPage: 1,
        pageSize: 5,
        unitId: '',
        communityId: '',
        buildingId: '',
        unitName: '',
        unitCode: '',
        unitLevel: '',
        unitAcreage: '',
        unitHaveElevator: '',
      },
      // 显示搜索条件
      showSearch: true,
      //状态字典(是否有电梯)
      statusOptions: [
        {
          dictValue: '0',  // 实际存储的值（提交到后端）
          dictLabel: '否' // 显示的文字（用户可见）
        },
        {
          dictValue: '1',
          dictLabel: '是'
        }
      ],
      options: [],//社区
      buildOptions: [],//楼栋
      //批量删除控制开关
      multiple: true,
      // 单元 表格数据
      unitList: [],
      // 遮罩层->查询数据是显示加载样式
      loading: true,
      // 分页总条数
      total: 0,
      //多选框选中的数据id
      ids: [],
      // 是否显示弹出层
      open: false,
      // 新增修改的表单参数
      form: {},
      title: "",
      // 修改或新增表单校验
      rules: {
        buildingId: [
          {required: true, message: "请选择楼栋", trigger: "blur"}
        ],
        unitLevel: [
          {required: true, message: "层数不能为空", trigger: "blur"},
          {pattern: /^[1-9]\d*$/, message: '请输入正确的整数格式', trigger: "change"}
        ],
        unitHaveElevator: [
          {required: true, message: "是否有电梯不能为空", trigger: "blur"}
        ],
        unitAcreage: [
          {required: true, message: "不能为空", trigger: "blur"}
        ],
        unitName: [
          {required: true, message: "不能为空", trigger: "blur"}
        ],
        unitCode: [
          {required: true, message: "不能为空", trigger: "blur"}
        ],
      }
    }
  },
  mounted() {
    this.getList()
    this.getAllCommunity()
    this.getAllBuilding()
  },
  methods: {
    //时间格式化的方法
    dateFormat(row, column, cellValue, index) {
      const daterc = row[column.property]
      if (daterc != null) {
        var date = new Date(daterc);
        var year = date.getFullYear();
        /* 在日期格式中，月份是从0开始，11结束，因此要加0
         * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
         * */
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        // 拼接
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
      }
    },
    /**多选框选中数据*/
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.unitId)
      console.log("ids=", this.ids)
      this.multiple = !selection.length
    },
    //当点击清除按钮清空输入内容时，触发 getList 方法--> 点击输入框的后面的X
    //查询数据
    getList() {
      this.loading = true
      this.$http.get('unit/selectUnitList', {params: this.queryParams})
          .then((res) => {
            this.total = res.data.total
            this.unitList = res.data.records
            this.$message.success(res.msg)
            this.loading = false
          })
          .catch((res) => {
            this.unitList = []
            this.$message.error(res.msg)
            this.loading = false
          })
    },
    //模糊查询的小区下拉框-查询并设置默认值
    getAllCommunity() {
      this.$http.get('build/getAllCommunity')
          .then((res) => {
            this.options = res.data
            this.queryParams.communityId = this.options[0].communityId
          })
          .catch((res) => {
            this.$message.error(res.msg)
          })
    },
    //模糊查询的楼栋下拉框-查询所有的
    getAllBuilding() {
      this.$http.get('build/getAllBuilding')
          .then((res) => {
            this.buildOptions = res.data
          })
          .catch((res) => {
            this.$message.error(res.msg)
          })
    },
    //当用户在输入框中按下回车键时，触发 handleQuery 方法
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    //重置按钮
    resetQuery() {
      this.reload();
    },
    //获取选中的小区
    selectedCommunity() {
      this.getList();
    },
    // 新增或修改表单重置
    reset() {
      this.form = {
        communityId: '',
        buildingId: '',
        unitName: '',
        unitCode: '',
        unitLevel: '',
        unitAcreage: '',
        unitHaveElevator: "",
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: '',
        remark: ''
      };
    },
    //新增按钮
    handleAdd() {
      this.reset();
      this.form.communityId = this.queryParams.communityId,
          this.open = true;
      this.title = "添加单元 ";
    },
    //修改或新增楼栋发送变化时触发
    selectedBuildingId() {

    },
    //单删+批量按钮
    handleDelete() {

    },
    //导出按钮
    handleExport() {
      console.log("ids=", this.ids)
      const requertUrl = `unit/getExcel?communityId=${this.queryParams.communityId}`
      this.$http.post(requertUrl, this.ids, {responseType: 'blob'})
          .then(response => {
            // 确认数据有效
            if (response.data.size === 0) {
              this.$message.error("文件为空");
              return;
            }
            // 创建下载链接
            const url = URL.createObjectURL(new Blob([response.data], {type: 'application/vnd.ms-excel'}));
            const link = document.createElement('a');
            link.href = url;
            //遍历找出社区名称
            let name = ""
            for (const item of this.options) {
              if (this.queryParams.communityId === item.communityId) {
                name = item.communityName
              }
            }
            link.download = name + '单元信息.xls';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
            this.$message.success("导出成功");
          })
          .catch(error => {
            this.$message.error("导出失败");
          });
    },
    //修改按钮
    handleUpdate(row) {
      console.log(row)
      this.reset();
      this.open = true;
      this.title = "修改单元 ";
      this.form = {
        unitId: row.unitId,
        buildingId: row.buildingId,
        communityId: this.queryParams.communityId,
        unitName: row.unitName,
        unitCode: row.unitCode,
        unitLevel: row.unitLevel,
        unitAcreage: row.unitAcreage,
        unitHaveElevator: row.unitHaveElevator,
        remark: row.remark
      }
    },
    //修改或新增表单提交按钮
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log("zy-unit->form=", this.form)
          let msg = (this.form.unitId !== undefined && this.form.unitId !== "") ? "修改" : "添加";
          this.$http.post("/unit/updateAndSaveUnit", this.form)
              .then((res) => {
                if (res.msg === "1") {
                  this.$message.error(msg + "失败,该小区楼栋下此单元已存在！")
                } else {
                  this.$message.success(msg + "成功！")
                  this.getList();
                  this.open = false;
                }
              })
              .catch((res) => {
                this.$message.error(res.msg)
              })
        }
      })
    },
    //修改或新增取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //每页条数变换时触发
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    //当前页发生改变触发
    handleCurrentChange(val) {
      this.queryParams.nowPage = val;
      this.getList();
    },
  }
}
</script>